package main

import (
	"context"
	"log"
	"net/http"
	"os"
	"time"

	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
	"github.com/joho/godotenv"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

var (
	client     *mongo.Client
	database   *mongo.Database
	collection *mongo.Collection
)

func main() {
	// 加载环境变量
	if err := godotenv.Load(); err != nil {
		log.Println("未找到.env文件，使用默认配置")
	}

	// 连接MongoDB
	connectMongoDB()

	// 加载删除状态
	loadDeletedState()

	// 创建Gin路由
	r := gin.Default()

	// 配置CORS
	r.Use(cors.New(cors.Config{
		AllowOrigins:     []string{"http://localhost:5173", "http://localhost:3000"},
		AllowMethods:     []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
		AllowHeaders:     []string{"Origin", "Content-Type", "Accept", "Authorization"},
		ExposeHeaders:    []string{"Content-Length"},
		AllowCredentials: true,
		MaxAge:           12 * time.Hour,
	}))

	// 注册路由
	setupRoutes(r)

	// 启动服务器
	port := os.Getenv("PORT")
	if port == "" {
		port = "8080"
	}

	log.Printf("服务器启动在端口 %s", port)
	log.Fatal(http.ListenAndServe(":"+port, r))
}

func connectMongoDB() {
	// MongoDB连接字符串
	mongoURI := os.Getenv("MONGODB_URI")
	if mongoURI == "" {
		mongoURI = "mongodb://localhost:27017"
	}

	// 创建客户端
	clientOptions := options.Client().ApplyURI(mongoURI)

	var err error
	client, err = mongo.Connect(context.TODO(), clientOptions)
	if err != nil {
		log.Fatal("连接MongoDB失败:", err)
	}

	// 测试连接
	err = client.Ping(context.TODO(), nil)
	if err != nil {
		log.Fatal("MongoDB连接测试失败:", err)
	}

	log.Println("成功连接到MongoDB")

	// 选择数据库和集合
	database = client.Database("kcloud")
	collection = database.Collection("users")

	// 初始化测试用户
	InitTestUser()
}

func setupRoutes(r *gin.Engine) {
	// API路由组
	api := r.Group("/api")
	{
		// 认证路由
		auth := api.Group("/auth")
		{
			auth.POST("/login", loginHandler)
			auth.GET("/profile", authMiddleware(), profileHandler)
		}

		// 镜像仓库路由
		registry := api.Group("/registry")
		registry.Use(authMiddleware()) // 需要认证
		{
			registry.GET("/health", checkRegistryHealth)
			registry.GET("/images", getImageList)
			registry.GET("/images/*name", getImageDetail)
			registry.GET("/tags/*name", getImageTags)
			registry.DELETE("/images/*name", deleteImage)
			registry.POST("/images/restore/*name", restoreImage)
			registry.POST("/images/upload", uploadImage)
			registry.GET("/upload/environment", checkUploadEnvironment)
			registry.GET("/config/delete", getDeleteConfig)
			registry.POST("/config/delete", setDeleteConfig)
		}

		// 应用部署路由
		api.POST("/deploy", authMiddleware(), deployApplication)
	}

	// 健康检查
	r.GET("/health", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"status": "ok",
			"time":   time.Now(),
		})
	})
}
